<script setup>
import { onBeforeUnmount, ref, nextTick, computed, watch,defineProps, onMounted } from 'vue'
import * as echarts from 'echarts'
import { marked } from 'marked';
import ecStat from 'echarts-stat'
echarts.registerTransform(ecStat.transform.regression)
import axios from 'axios';

const props = defineProps({
    waringId: Number
});
const id = ref(null)
const chartdata = ref([])
const startData = ref("")
const endData = ref("")
const minData = ref(null)
const maxData = ref(null)
const reDangerPaper = ref("")

// 添加渲染状态标记
const isChartRendered = ref(false);
const resizeObserver = ref(null);

const option = computed(() => {
    if (!minData.value || !maxData.value) return {};
    return {
    dataset: [
        {
            source: processedDataSource.value
        },
        {
            transform: {
                type: 'filter',
                config: {
                    // 筛选现有数据
                    dimension: 2, 
                    eq: 'current'
                }
            }
        },
        {
            transform: {
                type: 'filter',
                config: {
                    // 筛选预测数据
                    dimension: 2,
                    eq: 'forecast'
                }
            }
        },
        {
            transform: {
                type: 'ecStat:regression',
                config: {
                    method: 'logarithmic',
                    resultDimensions: ['x','y'] // x代表时间，y代表预测值
                }
            }
        }
    ],
    title: {
        text: '对该数据进行阶段性预测',
        left: 'center'
    },
    legend: {
        data: [startData.value,endData.value],
        bottom: 10
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    xAxis: {
        type: 'time', //  设置为时间轴
        splitLine: {
            lineStyle: {
                type: 'dashed'
            }
        },
        axisLabel: {
            formatter: function(value) {
                const date = new Date(value);
                return `${date.getFullYear()}`;
            }
        }
    },
    yAxis: {
        type: 'value',
        name: 'Value Size',
        splitLine: {
            lineStyle: {
                type: 'dashed'
            }
        }
    },
    visualMap: {
        show: false,
        dimension: 2,
        min: minData.value,
        max: maxData.value,
        seriesIndex: [0,1],
        inRange: {
            symbolSize: [80, 85]
        }
    },
    series: [
        {
            name: startData.value,
            type: 'scatter',
            datasetIndex: 1,
            symbolSize: (params) => Math.log(params[1] * 2000),
            encode: {
                x: 0, // 使用第1个维度作为x轴
                y: 1 // 使用第2个维度作为y轴
            }
        },
        {
            name: endData.value,
            type: 'scatter',
            datasetIndex: 2,
            symbolSize: (params) => Math.log(params[1] * 2000),
            encode: {
                x: 0, // 同上
                y: 1 // 同上
            }
        },
        {
            name: '趋势线',
            type: 'line',
            smooth: true,
            datasetIndex: 3,
            symbol: 'circle',
            symbolSize: (params) => Math.log(params[1] * 2),
            label: { show: false },
            encode: {
                x: 'x', // 使用transform后生成的x值作为x轴
                y: 'y' // 使用transform后生成的y值作为y轴
            }
        }
    ]
}});
const chartReDanger = ref(null)
let mychart = null

// 渲染Markdown内容
const renderMarkdown = (content) => {
    if (!content) {
        console.log(11);
        return "";
    }
    return marked(content); // 将markdown转为HTML
}
const convertDateToTimestamp = (dateStr) => {
    return new Date(dateStr).getTime();
}
// 转换数据源为时间戳格式
const processedDataSource = computed(() =>
    (chartdata.value || [] ).map(item => [
        convertDateToTimestamp(item[0]), // 转换日期为时间戳
        item[1], // 保留原始值
        item[2]
    ])
)

// ==================== 数据获取 ==================
const fetchData = () => {
    if (!props.waringId) {
        return;
    }
    try {
        fetchRedangerData(props.waringId)
    } catch (err) {
        console.error('数据请求失败', err);
    } finally {
        console.log(1111);
    }
}

// 获取
    const fetchRedangerData = async (dId) => {
        try {
            const response = await axios.get(`http://192.168.31.96:5000/redangerCharts/${dId}`)
            id.value = response.data.data.id;
            chartdata.value = response.data.data.chartdata;
            startData.value = response.data.data.startdata;
            endData.value = response.data.data.enddata;
            minData.value = response.data.data.mindata;
            maxData.value = response.data.data.maxdata;
            reDangerPaper.value = response.data.data.redangerpaper;
            console.log("bbbbbbbbb", response.data);
            console.log(id.value);
            console.log(chartdata.value);
            console.log(startData.value);
            console.log(endData.value);
            console.log(minData.value);
            console.log(maxData.value);
            console.log(reDangerPaper.value);
            // 确保DOM更新后渲染
            nextTick(() => {
                renderChart();
            });
        } catch (err) {
            console.error(err);
        } finally {
            console.log('更新结束');
        }
    }
watch(() => props.waringId, async (newId) => {
    if (newId) {
        fetchData();
    }
}, { immediate: true });
onBeforeUnmount(() => {
    if(mychart){
        mychart.dispose();
        mychart = null;
    }
})

// 修改：优化渲染函数
const renderChart = () => {
    // 确保容器存在且有数据
    if (!chartReDanger.value || chartdata.value.length === 0) {
        console.log('渲染条件不满足');
        return;
    }

    // 销毁旧实例
    if (mychart) {
        mychart.dispose();
        mychart = null;
    }

    // 确保容器可见
    nextTick(() => {
        if (chartReDanger.value.clientWidth <= 0) {
            setTimeout(renderChart, 100);
            return;
        }

        // 创建新实例
        mychart = echarts.init(chartReDanger.value);
        
        // 重要：使用option.value获取计算属性值
        mychart.setOption(option.value);
        mychart.resize();
        isChartRendered.value = true;
    });
};
// 添加响应式resize监听
onMounted(() => {
    resizeObserver.value = new ResizeObserver(() => {
        if (mychart) {
            mychart.resize();
        }
    });
    
    if (chartReDanger.value) {
        resizeObserver.value.observe(chartReDanger.value);
    }
});

onBeforeUnmount(() => {
    if (mychart) {
        resizeObserver.value?.unobserve(chartReDanger.value);
        mychart.dispose();
        mychart = null;
    }
});
</script>

<template>
<div class="dialog-content">
    <div class="reDanger-chart-paper-container">
        <div class="reDanger-chart">
            <div ref="chartReDanger" class="chart"></div>
        </div>
        <div class="reDanger-paper">
            <div class="paper-title">
                预警报告
            </div>
            <div class="paper-content" v-html="renderMarkdown(reDangerPaper)">
            </div>
        </div>
    </div>
    <div class="resolve-btn">
        <button>一键处理</button>
    </div>
</div>
</template>
<style>
.dialog-content {
    height: 800px;
    padding: 20px;
    display: flex;
    flex-direction: column;
}
.reDanger-chart-paper-container {
    display: flex; /* 使用 flex 布局 */
    flex: 1; /* 占据父容器的剩余空间 */
    gap: 20px; /* 设置两个子元素之间的间距 */
}
.reDanger-chart {
    min-width: 800px;
    min-height: 500px;
    flex: 2;
}
.chart {
    width: 100%;
    height: 100%;
}
.reDanger-paper {
    flex: 1;
    max-height: 500px;
    min-width: 300px;
    overflow: auto;
    /* background-color: #f9f9f9; */
    box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
    padding: 10px;
    border-radius: 5px;
}
.reDanger-paper .paper-title {
    font-size: 24px;
    color: rgb(0,81,255);
    font-weight: 600;
    margin-bottom: 10px;
}
.resolve-btn {
    margin-top: 20px;
    text-align: right;
}
.resolve-btn button {
    border-radius:20px;
    background-color: rgb(0,81,255);
    color: #fff;
    padding: 8px 10px;
    font-size: 18px;
    border: 0;
    cursor: pointer;
}


</style>